//
//  PartyCommentViewController.m
//  UESTCPioneer
//
//  Created by Apple on 14-5-18.
//  Copyright (c) 2014年 Sway. All rights reserved.
//

#import "PartyCommentViewController.h"
#import "PartyRefreshRequestViewController.h"
#import"commentView.h"
#import "commentTableViewCell.h"
#define backgroundColor [UIColor colorWithRed:237.0/255.0 green:237.0/255.0 blue:237.0/255.0 alpha:1]


#pragma mark - thinkReportTableViewCell

@interface thinkReportTableViewCell : UITableViewCell{
    /*add for 党课心得*/
    NSString * _reuseIdentifier;
    /*end add*/
    
}
@property  UIImageView *headImageView;
@property  UILabel *userName;
@property  UILabel *commentBody;


@end

@implementation thinkReportTableViewCell


//@ what the hell? 究竟怎么回事，为什么会多出35
-(void)setFrame:(CGRect)frame{
    frame.origin.y-=35;
    [super setFrame:frame];
}

-(id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    
    _reuseIdentifier = reuseIdentifier;
    self=[super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self){
        [self setBackgroundColor:backgroundColor];
        [self.contentView setBackgroundColor:backgroundColor];
        self.headImageView=[[UIImageView alloc]initWithFrame:CGRectMake(20, 10, 2, 2)];
        self.userName=[[UILabel alloc]initWithFrame:CGRectMake(44, 10, 100, 22)];
        self.commentBody=[[UILabel alloc]initWithFrame:CGRectMake(10, 44, 280, 60)];
        [self.commentBody setNumberOfLines:3];
        [self.contentView addSubview:self.headImageView];
        [self.contentView addSubview:self.userName];
        
        [self.contentView addSubview:self.commentBody];
        [self.headImageView setTranslatesAutoresizingMaskIntoConstraints:NO];
        [self.userName setTranslatesAutoresizingMaskIntoConstraints:NO];
        [self.commentBody setTranslatesAutoresizingMaskIntoConstraints:NO];
        
        [self.userName setFont:[UIFont systemFontOfSize:13]];
        [self.userName setTextColor:[UIColor colorWithRed:69.0/255.0 green:120.0/255.0 blue:200.0/255.0 alpha:1]];
        
        
        
        [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-10-[_headImageView(==22)]-[_userName]-|" options:0 metrics:0 views:NSDictionaryOfVariableBindings(_headImageView,_userName)]];
        
        [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-12-[_headImageView(==22)]" options:0 metrics:0 views:NSDictionaryOfVariableBindings(_headImageView)]];
        
        [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-12-[_userName(==22)]" options:0 metrics:0 views:NSDictionaryOfVariableBindings(_userName)]];
        
        
        [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-10-[_commentBody]-|" options:0 metrics:Nil views:NSDictionaryOfVariableBindings(_commentBody)]];
        
        [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[_userName]-[_commentBody]-|" options:0 metrics:Nil views:NSDictionaryOfVariableBindings(_commentBody,_userName)]];
        
    }
    return self;
}

@end


//#pragma mark - commentTableView
//
//@interface commentTableView : UPTableView
//
//
//@end
//
//@implementation commentTableView
//
//
//
//@end




@interface PartyCommentViewController ()<UITableViewDataSource,UITableViewDelegate,UITextViewDelegate>
{
    NSArray *tableViewDataArray;
    NSMutableArray *tableContentBodyFrameArray;
    UIImageView * tvImageView;
    NSString * text;
}

@property (nonatomic,strong) UITextView * questTV;
@property (nonatomic,strong) UIToolbar  * toolBar;
@property (nonatomic,strong) UIButton   * completeBtn;
@property (nonatomic,strong) UIButton   * cancelBtn;
@property (nonatomic,strong) UILabel    * tvLabel;
/*add for test*/
@property  (strong,nonatomic) PartyRefreshRequestViewController * sourceController;
/**/
@end
#pragma mark - commentViewController

static NSString *cellIdentifier=@"cell";
@implementation PartyCommentViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    [self.view setBackgroundColor:backgroundColor];
    [self.tableView setBackgroundColor:backgroundColor];
    tableViewTopConstraint.constant=0;
    [self.tableView registerClass:[commentTableViewCell class] forCellReuseIdentifier:cellIdentifier];
    self.tableView.delegate=self;
    self.tableView.dataSource=self;

    /*modify for  党课心得*/
    [self.completeBtn addTarget:self action:@selector(completeBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.toolBar addSubview:self.questTV];
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.toolBar];
    
    [self registerForKayboardNotifications];
    /*end*/
    text = [NSString string];
    tableContentBodyFrameArray = [NSMutableArray array];
}

//@设置评论数的方法
-(void)setNumberOfComment:(NSInteger)numberOfComment{
    _numberOfComment=numberOfComment;
    [self.navigationItem setRightBarButtonItem:Nil];
#pragma mark 加导航栏按钮
    UIButton *commentButton = [UIButton buttonWithType:UIButtonTypeCustom];
    
    UIImageView *imageView=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 18, 18)];
    [imageView setImage:[UIImage imageNamed:@"com.png"]];
    [commentButton addSubview:imageView];

    [commentButton setTitle:[NSString stringWithFormat:@"%d",self.numberOfComment] forState:UIControlStateNormal];
    [commentButton addTarget:self action:@selector(commentButtonPress:) forControlEvents:UIControlEventTouchUpInside];
    [commentButton setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 24, 24)];
    UIBarButtonItem *rightCommentBarButton=[helper BarButtonItemWithUIButton:commentButton ButtonOrigin:CGPointMake(46, 13) CustomViewSize:CGSizeMake(88, 44)];
    
    [self.navigationItem setRightBarButtonItem:rightCommentBarButton];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



#pragma mark - tableview Delegate and DataSource

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString * content = tableViewDataArray[indexPath.row][@"commentBody"];
    CGSize contentSize = [content sizeWithFont:[UIFont systemFontOfSize:14.0f] constrainedToSize:CGSizeMake(self.view.frame.size.width - 20, MAXFLOAT)];
    CGFloat height = contentSize.height;
    tableContentBodyFrameArray[indexPath.row] = [NSString stringWithFormat:@"%f",height];
    return height + 28.0f + 35.0f;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return  [tableViewDataArray count];
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    commentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
    [cell.headImageView setImageWithURL:tableViewDataArray[indexPath.row][@"headImageUrl"] placeholderImage:[UIImage imageNamed:@"defaultHeadImage.png"]];
    cell.userName.text=tableViewDataArray[indexPath.row][@"userName"];
    cell.commentBody.text=tableViewDataArray[indexPath.row][@"commentBody"];
    cell.commentTime.text = tableViewDataArray[indexPath.row][@"time"];
    if (![_commentFlag isEqualToString:@"PartyActivity"]) {
        cell.commentBack.hidden = YES;
    }
    [cell setCommentBodyFrame:[tableContentBodyFrameArray[indexPath.row] floatValue]];
    return cell;
}
#pragma mark - commentButton press

-(void)commentButtonPress:(UIButton*)button{
    
    if ([self.commenTag isEqualToString:@"ThinkingReport"]) {
        return;
    }
    
    __weak PartyCommentViewController *weakSelf=self;
    
    commentView *co=[[commentView alloc]init];
    
    /*写心得结束后执行的操作*/
    [co popUpCommentViewWithCommitBlock:^(NSString *commentBody) {
        NSMutableDictionary *dic= [[NSMutableDictionary alloc]initWithDictionary:weakSelf.commentRequestData];
        //        [weakSelf.commentRequestData setObject:@"comment" forKey:commentBody];
        dic[_commentContentKey]=commentBody;
        self.commentRequestData=[[NSDictionary alloc]initWithDictionary:dic];
        
        [NetworkCenter AFRequestWithData:self.commentRequestData SuccessBlock:^(AFHTTPRequestOperation *operation, id resultObject) {
            
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:resultObject options:NSJSONReadingMutableLeaves error:nil];
            
            if ([dic[@"result"] isEqualToString:@"success"]){
                [Alert showAlert:@"评论成功"];
                self.numberOfComment++;
                [self.tableView beginRefreshing];
            }
            else {
                [Alert showAlert:@"评论失败"];
            }
            
            //弹出提示：评论成功
            //            NSLog(@"评论成功");
            [co closeCommentView];
            //            [self _requestList];
            
        } FailureBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
            //弹出提示：评论失败
            NSLog(@"评论失败");
        }];
    }];
    /* end */
    
}

-(void)pullUpRefresh:(MJRefreshBaseView *)refreshView{
    NSMutableDictionary *tempDic = [[NSMutableDictionary alloc]initWithDictionary:self.commentListRequestData];
    
    [tempDic setObject:[NSString stringWithFormat:@"%d",PullUpRefreshTimes+2] forKey:@"page"];
    
    NSLog(@"page=%@",[NSString stringWithFormat:@"%d",PullUpRefreshTimes+2]);
    
    [NetworkCenter AFRequestWithData:tempDic SuccessBlock:^(AFHTTPRequestOperation *operation, id resultObject) {
        NSError *error;
        NSArray *arr=[NSJSONSerialization JSONObjectWithData:resultObject options:NSJSONReadingMutableLeaves error:&error];
        //如果空
        if ([arr count]==0){
            NSLog(@"[arr count] = %i",[arr count]);
            [refreshView endRefreshing];
            return ;
        }
  
        NSLog(@"arr = %@",arr);
        
        NSMutableArray *targetArray = [[NSMutableArray alloc]init];
        for (NSDictionary *sourceDic in arr){
            
            NSMutableDictionary *targetDic = [[NSMutableDictionary alloc]init];
 
            [targetDic setObject:@"" forKey:@"headImageUrl"];
            
            //@根据映射字典把服务器返回json的字段映射到本地字段如commentAuthor->userName,commentContent->commentBody
            NSEnumerator *keyEnumerator=[_commentListKeyMapping keyEnumerator];
            NSString *key;
            while((key=[keyEnumerator nextObject])!=nil){
                [targetDic setObject:sourceDic[key]  forKey:_commentListKeyMapping[key]];
            }
            
            NSLog(@"sourceDic[@content] = %@",sourceDic[@"content"]);
            if (sourceDic[@"content"]) {
                [targetDic setObject:sourceDic[@"content"] forKey:@"commentBody"];
                NSLog(@"targetDic = %@",targetDic);
            }
            
            [targetArray addObject:targetDic];
        }
        
        NSMutableArray *muArr = [[NSMutableArray alloc]initWithArray:tableViewDataArray];
        [muArr addObjectsFromArray:targetArray];
        tableViewDataArray = [[NSArray alloc]initWithArray:muArr];
        //        tableViewDataArray=targetArray;
        [refreshView endRefreshing];
        [self.tableView reloadData];
        PullUpRefreshTimes++;
    } FailureBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"commentViewController init request error:%@",error);
    }];
}


-(void)pullDownRefresh:(MJRefreshBaseView *)refreshView{
    [NetworkCenter AFRequestWithData:self.commentListRequestData SuccessBlock:^(AFHTTPRequestOperation *operation, id resultObject) {
        
        NSError *error;
        NSArray *arr=[NSJSONSerialization JSONObjectWithData:resultObject options:NSJSONReadingMutableLeaves error:&error];
        
        NSLog(@"返回 arr = %@",arr);
        NSMutableArray *targetArray = [[NSMutableArray alloc]init];
        for (NSDictionary *sourceDic in arr){
            
            NSMutableDictionary *targetDic = [[NSMutableDictionary alloc]init];
            [targetDic setObject:@"" forKey:@"headImageUrl"];
            
            //@根据映射字典把服务器返回json的字段映射到本地字段如commentAuthor->userName,commentContent->commentBody
            NSEnumerator *keyEnumerator=[_commentListKeyMapping keyEnumerator];
            NSString *key;
            while((key=[keyEnumerator nextObject])!=nil){
                [targetDic setObject:sourceDic[key]  forKey:_commentListKeyMapping[key]];
            }
            NSLog(@"sourceDic[@content] = %@",sourceDic[@"content"]);
            if (sourceDic[@"content"]) {
                [targetDic setObject:sourceDic[@"content"] forKey:@"commentBody"];
                NSLog(@"targetDic = %@",targetDic);
            }
            [targetArray addObject:targetDic];
            NSLog(@"targetArray = %@",targetArray);
        }
        tableViewDataArray=targetArray;
        NSLog(@"tableViewDataArray = %@",tableViewDataArray);
        [refreshView endRefreshing];
        [self.tableView reloadData];
    } FailureBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"commentViewController init request error:%@",error);
    }];
}

/****************************************************************************************/
/*add for 党课心得*/
-(void)_loadUPTableView{
    self.tableView=[[UPTableView alloc]initWithFrame:CGRectMake(0, 0, 320,self.view.frame.size.height - 35 - 64) style:UITableViewStyleGrouped];
    self.tableView.tag = 27;
    [self.view addSubview:self.tableView];
}


-(UITextView *)questTV{
    if (!_questTV) {
        _questTV = [[UITextView alloc] initWithFrame:CGRectMake(15, 5, self.view.frame.size.width - 30, 25)];
        _questTV.editable = YES;
//        _questTV.backgroundColor = self.tableView.backgroundColor;
        _questTV.delegate = self;
        _questTV.font = [UIFont systemFontOfSize:13];
        _questTV.textContainerInset = UIEdgeInsetsMake(5, 21, 5, 15);
        
        _questTV.layer.borderWidth = 1;
        _questTV.layer.borderColor = [[UIColor colorWithWhite:185.0/255.0 alpha:1] CGColor];
        _questTV.text = @"写心得";
        _questTV.textColor = [UIColor colorWithWhite:149.0/255.0 alpha:1];
        
        tvImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"write1.png"]];
        tvImageView.frame = CGRectMake(5, 5, 15, 15);
        [_questTV addSubview:tvImageView];
        
        
    }
    return _questTV;
}

-(UILabel *)tvLabel{
    if (!_tvLabel) {
        _tvLabel = [[UILabel alloc] initWithFrame:CGRectMake(30, 5, 200, 20)];
    }
    return _tvLabel;
}

- (UIToolbar *)toolBar{
    if (!_toolBar) {
        _toolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, self.tableView.frame.origin.y + self.tableView.frame.size.height , self.view.frame.size.width , 35)];
    }
    return _toolBar;
}



- (UIButton *)completeBtn{
    if (!_completeBtn) {
        _completeBtn = [[UIButton alloc] initWithFrame:CGRectMake(270, 0, 40, 40)];
        _completeBtn.contentEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
        [_completeBtn setImage:[UIImage imageNamed:@"complete1.png"] forState:UIControlStateNormal];
        //   [_completeBtn setBackgroundImage:[UIImage imageNamed:@"complete1.png"] forState:UIControlStateNormal];
        _completeBtn.enabled = NO;
        
    }
    return _completeBtn;
}

- (UIButton *)cancelBtn{
    if (!_cancelBtn) {
        _cancelBtn = [[UIButton alloc] initWithFrame:CGRectMake(10, 2, 35, 35)];
        _cancelBtn.contentEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
        [_cancelBtn setImage:[UIImage imageNamed:@"cancel.png"] forState:UIControlStateNormal];
        [self.cancelBtn addTarget:self action:@selector(cancelBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _cancelBtn;
}


#pragma mark  UITextViewDelegate协议
- (void)textViewDidBeginEditing:(UITextView *)textView{
    
    //  self.toolBar.frame = CGRectMake(self.toolBar.frame.origin.x, self.toolBar.frame.origin.y - keyBoardHeight - 50, self.view.frame.size.width, self.toolBar.frame.size.height - 50);
    
    [self.tableView setScrollEnabled:NO];
    [self.tableView setAllowsSelection:NO];
    self.questTV.frame = CGRectMake(20, 40, 280, 100);
    self.questTV.textContainerInset = UIEdgeInsetsZero;
    self.questTV.text = text;
    self.questTV.font = [UIFont systemFontOfSize:16];
    self.questTV.textColor = [UIColor blackColor];
    tvImageView.hidden = YES;
    
    self.tvLabel.center = CGPointMake(self.view.frame.size.width/2, 20);
    self.tvLabel.text = @"写心得";
    self.tvLabel.textAlignment = NSTextAlignmentCenter;
    self.tvLabel.hidden = NO;
    self.cancelBtn.hidden = NO;
    self.completeBtn.hidden = NO;
    
    [self.toolBar addSubview:self.tvLabel];
    [self.toolBar addSubview:self.completeBtn];
    [self.toolBar addSubview:self.cancelBtn];
}

- (void)textViewDidChange:(UITextView *)textView{
    if (self.questTV.text.length != 0) {
        self.completeBtn.enabled = YES;
        [self.completeBtn setImage:[UIImage imageNamed:@"complete2.png"] forState:UIControlStateNormal];
    }else
        self.completeBtn.enabled = NO;
    text = textView.text;
}

-(void)textViewDidEndEditing:(UITextView *)textView{
    self.questTV.font = [UIFont systemFontOfSize:13];
    [self.tableView setScrollEnabled:YES];
}

- (void)cancelBtnClick:(UIButton *)sender{
    [self.questTV resignFirstResponder];
    [self toolBarChanged];
}

- (void)completeBtnClick:(UIButton *)sender {
    [self.questTV resignFirstResponder];
    self.questTV.text = NULL;
    [self toolBarChanged];
    self.completeBtn.enabled = NO;
    
    
    __weak PartyCommentViewController *weakSelf=self;
    NSMutableDictionary *dic= [[NSMutableDictionary alloc]initWithDictionary:weakSelf.commentRequestData];
    
    dic[_commentContentKey]=text;
    self.commentRequestData=[[NSDictionary alloc]initWithDictionary:dic];
    [NetworkCenter AFRequestWithData:self.commentRequestData SuccessBlock:^(AFHTTPRequestOperation *operation, id resultObject) {

        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:resultObject options:NSJSONReadingMutableLeaves error:nil];        

        if ([dic[@"result"] isEqualToString:@"success"]){
            [Alert showAlert:@"提交心得成功!"];
            text = NULL;
//            self.questTV.text = text;
            self.numberOfComment++;
            [self.tableView beginRefreshing];
        }
        else {
            [Alert showAlert:@"提交心得失败!"];
            text = NULL;
        }
        
    } FailureBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        [Alert showAlert:@"网络请求失败!"];
    }];
}

- (void)toolBarChanged{
    self.completeBtn.hidden = YES;
    self.cancelBtn.hidden = YES;
    self.tvLabel.hidden = YES;
    self.toolBar.frame = CGRectMake(0, self.tableView.frame.origin.y + self.tableView.frame.size.height , self.view.frame.size.width , 35);
    self.questTV.frame = CGRectMake(self.questTV.frame.origin.x, 5, self.view.frame.size.width - 30, 25);
    if (self.questTV.text.length == 0) {
        self.questTV.text = @"写心得";
        self.questTV.textColor = [UIColor colorWithWhite:149.0/255.0 alpha:1];
        tvImageView.hidden = NO;
        self.questTV.textContainerInset = UIEdgeInsetsMake(5, 21, 5, 15);
    }else{
        self.questTV.contentInset = UIEdgeInsetsMake(5, 0, 5, 0);
        self.questTV.textColor = [UIColor blackColor];
    }
    
    
}

- (void)registerForKayboardNotifications{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardwillHidden:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)keyboardChange:(NSNotification *)aNotification{
    NSDictionary * info = [aNotification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    /*
     [UIView beginAnimations:nil context:NULL];
     [UIView setAnimationDelegate:self];
     [UIView setAnimationDuration:0.0];
     [UIView setAnimationBeginsFromCurrentState:YES];
     */
    [UIView animateWithDuration:[[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue]
                     animations:^{
                         self.toolBar.frame = CGRectMake(self.toolBar.frame.origin.x, self.tableView.frame.origin.y + self.tableView.frame.size.height - kbSize.height - 120, self.view.frame.size.width, self.toolBar.frame.size.height + 150);
                     }];
    //  [UIView commitAnimations];
}

- (void)keyboardwillHidden:(NSNotification *)aNotification{
}


-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    self.sourceController= segue.sourceViewController;
}
#pragma mark -CommentNumDelegate代理方法
-(void)resetCommentCount:(NSIndexPath *)indexPath{
//    self.sourceController.cell3
}
@end
